package com.nku.mason.lucene.optimization;

import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;

import com.nku.mason.lucene.entity.Article;
import com.nku.mason.lucene.util.LuceneUtil;

/**
 * 索引库优化，文件数量和大小问题(合并文件--->indexWriter的optimize和merge)
 * @author Mason
 *
 */
public class FileMerge {
	
	public void createIndexDB() throws Exception{
		Article article = new Article(1,"大学","南开大学欢迎你,好想回家");
		IndexWriter indexWriter = new IndexWriter(LuceneUtil.getDirectory(), LuceneUtil.getAnalyzer(), LuceneUtil.getMaxFieldLength());
		indexWriter.addDocument(LuceneUtil.javabean2Document(article));
		System.out.println("New Document added...");
		//在写入document对象后优化合并.cfs文件
		//indexWriter.optimize();
		//或者设置mergeFactor，来设置合并文件的个数阈值
		indexWriter.setMergeFactor(3);
		indexWriter.close();
	}
	
	public void searchForKeyword(String keyword) throws Exception{
		List<Article> list = new ArrayList<>();
		IndexSearcher indexSearcher = new IndexSearcher(LuceneUtil.getDirectory());
		QueryParser queryParser = new QueryParser(LuceneUtil.getVersion(), "content", LuceneUtil.getAnalyzer());
		Query query = queryParser.parse(keyword);
		TopDocs topDocs = indexSearcher.search(query, 100);
		for(int i=0;i<topDocs.scoreDocs.length;i++){
			int no = topDocs.scoreDocs[i].doc;
			Document document = indexSearcher.doc(no);
			Article article = (Article) LuceneUtil.document2JavaBean(document, Article.class);
			list.add(article);
		}
		indexSearcher.close();
		
		for(Article a:list){
			System.out.println(a);
		}
	}
	
	public static void main(String[] args) throws Exception {
		FileMerge test = new FileMerge();
//		test.createIndexDB();
		test.searchForKeyword("南");
	}
}
